package com.example.demo.exception;


import com.alibaba.fastjson.JSONObject;
import com.example.demo.handler.AuthenticationEntryPointImpl;
import com.example.demo.pojo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * @author 麦翔盛
 * @description: 全局异常处理类
 * 需要先自定义一个异常 再对异常进行捕获处理 处理的需要返回一个返回的map
 * @date 2022/11/21 15:56
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限认证处理 直接抛出
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public void mySecurityExceptionHanlder(AccessDeniedException e){
        logger.error("-------------全局异常处理拦截开始-------------");
        logger.error("AccessDeniedException:"+e.getMessage()+","+e);
        e.printStackTrace();
        String errJsonStr = JSONObject.toJSONString(e);

        logger.error("错误信息:【 {} 】",errJsonStr);

        logger.error("-------------全局异常处理拦截结束-------------");

        // 不处理抛出 让全局自定义异常去处理
        throw e;

//        return new ResponseResult(502,e.getDescription());
    }



    @ExceptionHandler(MySecurityException.class)
    public ResponseResult mySecurityExceptionHanlder(MySecurityException e){
        logger.error("MySecurityException:"+e.getDescription()+","+e);
        e.printStackTrace();
        String errJsonStr = JSONObject.toJSONString(e);

        logger.error("错误信息:【 {} 】",errJsonStr);


        return new ResponseResult(502,e.getDescription());
    }


    /**
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult runtimeExceptionHandler(RuntimeException e){
        logger.error("RuntimeException:"+e.getMessage()+","+e);
        e.printStackTrace();
        String errJsonStr = JSONObject.toJSONString(e);

        logger.error("错误信息:【 {} 】",errJsonStr);


        return new ResponseResult(501,e.getMessage());
    }
}
